import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { toast } from 'sonner';
import {
  Users,
  Plus,
  Search,
  Filter,
  Edit,
  Trash2,
  Eye,
  UserPlus,
  Shield,
  Mail,
  Phone,
  Calendar,
  Building,
  Briefcase,
  MoreHorizontal,
  RefreshCw,
  Download,
  Upload
} from 'lucide-react';

/**
 * 用户数据类型定义
 */
interface User {
  id: number;
  username: string;
  email: string;
  full_name: string;
  avatar?: string;
  phone?: string;
  department?: string;
  position?: string;
  is_active: boolean;
  roles: string[];
  permissions: string[];
  created_at: string;
  updated_at?: string;
  last_login?: string;
}

/**
 * 用户表单数据类型定义
 */
interface UserFormData {
  username: string;
  email: string;
  full_name: string;
  phone?: string;
  department?: string;
  position?: string;
  password?: string;
  is_active: boolean;
  roles: string[];
}

/**
 * 模拟用户数据
 */
const mockUsers: User[] = [
  {
    id: 1,
    username: 'admin',
    email: 'admin@company.com',
    full_name: '系统管理员',
    phone: '13800138000',
    department: 'IT部门',
    position: '系统管理员',
    is_active: true,
    roles: ['admin', 'user'],
    permissions: ['user:read', 'user:create', 'user:update', 'user:delete'],
    created_at: '2024-01-01T00:00:00Z',
    last_login: '2024-01-15T10:30:00Z'
  },
  {
    id: 2,
    username: 'manager',
    email: 'manager@company.com',
    full_name: '项目经理',
    phone: '13800138001',
    department: '产品部门',
    position: '项目经理',
    is_active: true,
    roles: ['manager', 'user'],
    permissions: ['user:read', 'project:manage'],
    created_at: '2024-01-02T00:00:00Z',
    last_login: '2024-01-15T09:15:00Z'
  },
  {
    id: 3,
    username: 'developer',
    email: 'developer@company.com',
    full_name: '开发工程师',
    phone: '13800138002',
    department: '技术部门',
    position: '高级开发工程师',
    is_active: true,
    roles: ['developer', 'user'],
    permissions: ['user:read', 'code:write'],
    created_at: '2024-01-03T00:00:00Z',
    last_login: '2024-01-15T08:45:00Z'
  },
  {
    id: 4,
    username: 'designer',
    email: 'designer@company.com',
    full_name: 'UI设计师',
    phone: '13800138003',
    department: '设计部门',
    position: 'UI/UX设计师',
    is_active: false,
    roles: ['designer', 'user'],
    permissions: ['user:read', 'design:create'],
    created_at: '2024-01-04T00:00:00Z',
    last_login: '2024-01-10T16:20:00Z'
  },
  {
    id: 5,
    username: 'analyst',
    email: 'analyst@company.com',
    full_name: '数据分析师',
    phone: '13800138004',
    department: '数据部门',
    position: '高级数据分析师',
    is_active: true,
    roles: ['analyst', 'user'],
    permissions: ['user:read', 'data:analyze'],
    created_at: '2024-01-05T00:00:00Z',
    last_login: '2024-01-14T14:20:00Z'
  }
];

/**
 * 角色选项配置
 */
const roleOptions = [
  { value: 'admin', label: '管理员' },
  { value: 'manager', label: '项目经理' },
  { value: 'developer', label: '开发人员' },
  { value: 'designer', label: '设计师' },
  { value: 'analyst', label: '数据分析师' },
  { value: 'user', label: '普通用户' }
];

/**
 * 部门选项配置
 */
const departmentOptions = [
  'IT部门',
  '产品部门',
  '技术部门',
  '设计部门',
  '数据部门',
  '市场部门',
  '销售部门',
  '人事部门',
  '财务部门'
];

/**
 * 用户管理页面主组件
 */
export default function UserManagementPage() {
  // 状态管理
  const [users, setUsers] = useState<User[]>(mockUsers);
  const [filteredUsers, setFilteredUsers] = useState<User[]>(mockUsers);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [roleFilter, setRoleFilter] = useState<string>('all');
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(false);

  // 表单数据状态
  const [formData, setFormData] = useState<UserFormData>({
    username: '',
    email: '',
    full_name: '',
    phone: '',
    department: '',
    position: '',
    password: '',
    is_active: true,
    roles: ['user']
  });

  /**
   * 过滤用户列表
   * 根据搜索词、状态和角色进行过滤
   */
  useEffect(() => {
    let filtered = users;

    // 搜索过滤
    if (searchTerm) {
      filtered = filtered.filter(user => 
        user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
        user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
        user.full_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        user.department?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    // 状态过滤
    if (statusFilter !== 'all') {
      filtered = filtered.filter(user => 
        statusFilter === 'active' ? user.is_active : !user.is_active
      );
    }

    // 角色过滤
    if (roleFilter !== 'all') {
      filtered = filtered.filter(user => 
        user.roles.includes(roleFilter)
      );
    }

    setFilteredUsers(filtered);
  }, [users, searchTerm, statusFilter, roleFilter]);

  /**
   * 重置表单数据
   */
  const resetFormData = () => {
    setFormData({
      username: '',
      email: '',
      full_name: '',
      phone: '',
      department: '',
      position: '',
      password: '',
      is_active: true,
      roles: ['user']
    });
  };

  /**
   * 处理创建用户
   */
  const handleCreateUser = async () => {
    setLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const newUser: User = {
        id: Date.now(),
        ...formData,
        permissions: ['user:read'],
        created_at: new Date().toISOString(),
      };
      
      setUsers(prev => [...prev, newUser]);
      setShowCreateDialog(false);
      resetFormData();
      toast.success('用户创建成功');
    } catch (error) {
      toast.error('创建用户失败');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 处理编辑用户
   */
  const handleEditUser = async () => {
    if (!selectedUser) return;
    
    setLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setUsers(prev => prev.map(user => 
        user.id === selectedUser.id 
          ? { ...user, ...formData, updated_at: new Date().toISOString() }
          : user
      ));
      
      setShowEditDialog(false);
      setSelectedUser(null);
      resetFormData();
      toast.success('用户信息更新成功');
    } catch (error) {
      toast.error('更新用户信息失败');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 处理删除用户
   */
  const handleDeleteUser = async (userId: number) => {
    setLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setUsers(prev => prev.filter(user => user.id !== userId));
      toast.success('用户删除成功');
    } catch (error) {
      toast.error('删除用户失败');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 打开编辑对话框
   */
  const openEditDialog = (user: User) => {
    setSelectedUser(user);
    setFormData({
      username: user.username,
      email: user.email,
      full_name: user.full_name,
      phone: user.phone || '',
      department: user.department || '',
      position: user.position || '',
      is_active: user.is_active,
      roles: user.roles
    });
    setShowEditDialog(true);
  };

  /**
   * 切换用户状态
   */
  const toggleUserStatus = async (userId: number) => {
    setLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      setUsers(prev => prev.map(user => 
        user.id === userId 
          ? { ...user, is_active: !user.is_active, updated_at: new Date().toISOString() }
          : user
      ));
      
      toast.success('用户状态更新成功');
    } catch (error) {
      toast.error('更新用户状态失败');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 格式化日期显示
   */
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN');
  };

  /**
   * 获取角色标签颜色
   */
  const getRoleBadgeColor = (role: string) => {
    const colors = {
      admin: 'bg-red-100 text-red-800',
      manager: 'bg-blue-100 text-blue-800',
      developer: 'bg-green-100 text-green-800',
      designer: 'bg-purple-100 text-purple-800',
      analyst: 'bg-yellow-100 text-yellow-800',
      user: 'bg-gray-100 text-gray-800'
    };
    return colors[role as keyof typeof colors] || colors.user;
  };

  /**
   * 处理导出用户数据
   */
  const handleExportUsers = () => {
    const csvContent = "data:text/csv;charset=utf-8," 
      + "用户名,邮箱,姓名,手机,部门,职位,状态,角色,创建时间\n"
      + users.map(user => 
          `${user.username},${user.email},${user.full_name},${user.phone || ''},${user.department || ''},${user.position || ''},${user.is_active ? '活跃' : '禁用'},${user.roles.join(';')},${formatDate(user.created_at)}`
        ).join("\n");
    
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "users.csv");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    toast.success('用户数据导出成功');
  };

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* 页面标题 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">用户管理</h1>
            <p className="text-gray-600 mt-1">管理系统用户账户和权限</p>
          </div>
          <div className="flex space-x-3">
            <Button variant="outline" size="sm">
              <Upload className="w-4 h-4 mr-2" />
              导入用户
            </Button>
            <Button variant="outline" size="sm" onClick={handleExportUsers}>
              <Download className="w-4 h-4 mr-2" />
              导出用户
            </Button>
            <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
              <DialogTrigger asChild>
                <Button size="sm">
                  <Plus className="w-4 h-4 mr-2" />
                  添加用户
                </Button>
              </DialogTrigger>
              <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                  <DialogTitle>创建新用户</DialogTitle>
                  <DialogDescription>
                    填写用户基本信息和权限设置
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <label className="text-sm font-medium">用户名 *</label>
                      <Input
                        value={formData.username}
                        onChange={(e) => setFormData(prev => ({ ...prev, username: e.target.value }))}
                        placeholder="请输入用户名"
                      />
                    </div>
                    <div className="space-y-2">
                      <label className="text-sm font-medium">邮箱 *</label>
                      <Input
                        type="email"
                        value={formData.email}
                        onChange={(e) => setFormData(prev => ({ ...prev, email: e.target.value }))}
                        placeholder="请输入邮箱"
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium">姓名 *</label>
                    <Input
                      value={formData.full_name}
                      onChange={(e) => setFormData(prev => ({ ...prev, full_name: e.target.value }))}
                      placeholder="请输入真实姓名"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <label className="text-sm font-medium">手机号</label>
                      <Input
                        value={formData.phone}
                        onChange={(e) => setFormData(prev => ({ ...prev, phone: e.target.value }))}
                        placeholder="请输入手机号"
                      />
                    </div>
                    <div className="space-y-2">
                      <label className="text-sm font-medium">部门</label>
                      <Select value={formData.department} onValueChange={(value) => setFormData(prev => ({ ...prev, department: value }))}>
                        <SelectTrigger>
                          <SelectValue placeholder="选择部门" />
                        </SelectTrigger>
                        <SelectContent>
                          {departmentOptions.map(dept => (
                            <SelectItem key={dept} value={dept}>{dept}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium">职位</label>
                    <Input
                      value={formData.position}
                      onChange={(e) => setFormData(prev => ({ ...prev, position: e.target.value }))}
                      placeholder="请输入职位"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium">密码 *</label>
                    <Input
                      type="password"
                      value={formData.password}
                      onChange={(e) => setFormData(prev => ({ ...prev, password: e.target.value }))}
                      placeholder="请输入密码"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium">角色</label>
                    <Select value={formData.roles[0]} onValueChange={(value) => setFormData(prev => ({ ...prev, roles: [value] }))}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择角色" />
                      </SelectTrigger>
                      <SelectContent>
                        {roleOptions.map(role => (
                          <SelectItem key={role.value} value={role.value}>{role.label}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setShowCreateDialog(false)}>
                    取消
                  </Button>
                  <Button onClick={handleCreateUser} disabled={loading}>
                    {loading ? '创建中...' : '创建用户'}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>

        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">总用户数</p>
                  <p className="text-2xl font-bold text-gray-900">{users.length}</p>
                </div>
                <Users className="w-8 h-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">活跃用户</p>
                  <p className="text-2xl font-bold text-gray-900">{users.filter(u => u.is_active).length}</p>
                </div>
                <UserPlus className="w-8 h-8 text-green-600" />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">管理员</p>
                  <p className="text-2xl font-bold text-gray-900">{users.filter(u => u.roles.includes('admin')).length}</p>
                </div>
                <Shield className="w-8 h-8 text-red-600" />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">今日新增</p>
                  <p className="text-2xl font-bold text-gray-900">3</p>
                </div>
                <Calendar className="w-8 h-8 text-purple-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 搜索和过滤 */}
        <Card>
          <CardContent className="p-6">
            <div className="flex flex-col md:flex-row gap-4">
              <div className="flex-1">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                  <Input
                    placeholder="搜索用户名、邮箱、姓名或部门..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>
              <div className="flex gap-2">
                <Select value={statusFilter} onValueChange={setStatusFilter}>
                  <SelectTrigger className="w-32">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部状态</SelectItem>
                    <SelectItem value="active">活跃</SelectItem>
                    <SelectItem value="inactive">禁用</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={roleFilter} onValueChange={setRoleFilter}>
                  <SelectTrigger className="w-32">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部角色</SelectItem>
                    {roleOptions.map(role => (
                      <SelectItem key={role.value} value={role.value}>{role.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Button variant="outline" size="sm">
                  <RefreshCw className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 用户列表 */}
        <Card>
          <CardHeader>
            <CardTitle>用户列表</CardTitle>
            <CardDescription>共 {filteredUsers.length} 个用户</CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>用户信息</TableHead>
                  <TableHead>联系方式</TableHead>
                  <TableHead>部门职位</TableHead>
                  <TableHead>角色</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>最后登录</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredUsers.map((user) => (
                  <TableRow key={user.id}>
                    <TableCell>
                      <div className="flex items-center space-x-3">
                        <div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center text-white text-sm font-medium">
                          {user.full_name.charAt(0)}
                        </div>
                        <div>
                          <div className="font-medium">{user.full_name}</div>
                          <div className="text-sm text-gray-500">@{user.username}</div>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="flex items-center text-sm">
                          <Mail className="w-3 h-3 mr-1 text-gray-400" />
                          {user.email}
                        </div>
                        {user.phone && (
                          <div className="flex items-center text-sm text-gray-500">
                            <Phone className="w-3 h-3 mr-1 text-gray-400" />
                            {user.phone}
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        {user.department && (
                          <div className="flex items-center text-sm">
                            <Building className="w-3 h-3 mr-1 text-gray-400" />
                            {user.department}
                          </div>
                        )}
                        {user.position && (
                          <div className="flex items-center text-sm text-gray-500">
                            <Briefcase className="w-3 h-3 mr-1 text-gray-400" />
                            {user.position}
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1">
                        {user.roles.map((role) => (
                          <Badge key={role} className={`text-xs ${getRoleBadgeColor(role)}`}>
                            {roleOptions.find(r => r.value === role)?.label || role}
                          </Badge>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge 
                        className={`cursor-pointer ${
                          user.is_active 
                            ? 'bg-green-100 text-green-800 hover:bg-green-200' 
                            : 'bg-red-100 text-red-800 hover:bg-red-200'
                        }`}
                        onClick={() => toggleUserStatus(user.id)}
                      >
                        {user.is_active ? '活跃' : '禁用'}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="text-sm text-gray-500">
                        {user.last_login ? formatDate(user.last_login) : '从未登录'}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => openEditDialog(user)}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <Button variant="ghost" size="sm">
                              <Trash2 className="w-4 h-4 text-red-500" />
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>确认删除用户</AlertDialogTitle>
                              <AlertDialogDescription>
                                确定要删除用户 "{user.full_name}" 吗？此操作不可撤销。
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>取消</AlertDialogCancel>
                              <AlertDialogAction
                                onClick={() => handleDeleteUser(user.id)}
                                className="bg-red-600 hover:bg-red-700"
                              >
                                删除
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        {/* 编辑用户对话框 */}
        <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>编辑用户信息</DialogTitle>
              <DialogDescription>
                修改用户的基本信息和权限设置
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">用户名</label>
                  <Input
                    value={formData.username}
                    onChange={(e) => setFormData(prev => ({ ...prev, username: e.target.value }))}
                    placeholder="请输入用户名"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">邮箱</label>
                  <Input
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData(prev => ({ ...prev, email: e.target.value }))}
                    placeholder="请输入邮箱"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">姓名</label>
                <Input
                  value={formData.full_name}
                  onChange={(e) => setFormData(prev => ({ ...prev, full_name: e.target.value }))}
                  placeholder="请输入真实姓名"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">手机号</label>
                  <Input
                    value={formData.phone}
                    onChange={(e) => setFormData(prev => ({ ...prev, phone: e.target.value }))}
                    placeholder="请输入手机号"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">部门</label>
                  <Select value={formData.department} onValueChange={(value) => setFormData(prev => ({ ...prev, department: value }))}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择部门" />
                    </SelectTrigger>
                    <SelectContent>
                      {departmentOptions.map(dept => (
                        <SelectItem key={dept} value={dept}>{dept}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">职位</label>
                <Input
                  value={formData.position}
                  onChange={(e) => setFormData(prev => ({ ...prev, position: e.target.value }))}
                  placeholder="请输入职位"
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">角色</label>
                <Select value={formData.roles[0]} onValueChange={(value) => setFormData(prev => ({ ...prev, roles: [value] }))}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择角色" />
                  </SelectTrigger>
                  <SelectContent>
                    {roleOptions.map(role => (
                      <SelectItem key={role.value} value={role.value}>{role.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setShowEditDialog(false)}>
                取消
              </Button>
              <Button onClick={handleEditUser} disabled={loading}>
                {loading ? '保存中...' : '保存更改'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </div>
  );
}